/**
 * 
 */
package spring.mvc.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * @author NhungHTH1
 * 
 */
public class JPAUtil {
	private static EntityManagerFactory entityManagerFactory = null;

	private static InheritableThreadLocal<EntityManager> entityManagerThreadLocal = new InheritableThreadLocal<EntityManager>();

	static {
		try {
			// use JPA APIs
			// FSU like the persistence unit name decalred in persistence.xml,
			// at line: persistence-unit name="FSU"
			entityManagerFactory = Persistence
					.createEntityManagerFactory("fma");
			
			System.out.println("Created persistence name!!!");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Get the configured entityManagerFactory
	 * 
	 * @return entityManagerFactory
	 */
	public static EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	/**
	 * Get entity manager from thread
	 * 
	 * @return entity manager
	 */
	public static EntityManager getEntityManager() {
		if (entityManagerThreadLocal.get() == null
				|| entityManagerThreadLocal.get().isOpen() == false) {
			entityManagerThreadLocal.set(entityManagerFactory
					.createEntityManager());
		}
		return entityManagerThreadLocal.get();
	}
}
